<?php
namespace classlib\loger;
use classlib\acl;
class db extends log_abstract {
    /**
     * DB日志构造函数
     * @param string $level 日志记录开启等级
     */
    public function __construct($param) {
    	$this->level   = isset($param['lv'])? intval($param['lv']):self::LOG_DEBUG;
    	$this->channal = isset($param['model'])? $param['model']:'main.sys.syslog';
    }
    
    //获取当前登录账号的用户名
    private static function get_user() {
    	$user  = '匿名';
    	foreach (\classlib\acl::$acl as $acls) {
    		foreach ($acls as $acl) {
    			if ($acl->user) {
    				$user = $acl->user['id'];
    				break;
    			}
    		}
    	}
    	return $user;
    }
    
    /**
     * 记录日志操作
     * @param string $msg 日志数据(数组)
     * @param int    $lv  日志错误等级 
     * @param string $prefix 日志文件前缀
     * @return boolean 返回是否记录成功
     */
    public function write($msg, $lv=log_abstract::LOG_ERR, $prefix='web') {
		if($lv > $this->level) {
			return;
		}
		$user  = self::get_user();
		$ip    = \classlib\core\get_ip();
		$msg   = str_replace(array("\n", "\r"), '', $msg);
		$path  = (!isset($_SERVER['REQUEST_URI']))? '匿名来源':$_SERVER['REQUEST_URI'];
		$field = array('type'=>$lv, 'path'=>$path, 'user'=>$user,
			'msg'=>$msg, 'ip'=>$ip, 'stime'=>time());
		\classlib\core\model::load($this->channal)->new_one($field);
    }
    
    /**
     * 析构的时候回收文件句柄
     * @return void
     */
    public function __destruct() {
    }
}